package com.hz.friends.db;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import com.hz.friends.chat.entity.IMChatMessage;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;

public class DBMessageManager {
	private DBHelper helper;
	private SQLiteDatabase db;
	private int pageSize = 30;

	public DBMessageManager(Context context) {
		helper = new DBHelper(context);
		// 因为getWritableDatabase内部调用了mContext.openOrCreateDatabase(mName, 0,
		// mFactory);
		// 所以要确保context已初始化,我们可以把实例化DBManager的步骤放在Activity的onCreate里
		db = helper.getWritableDatabase();
	}

	/**
	 * 保存一条消息
	 * 
	 * @param chatmsg
	 */
	public void save(IMChatMessage chatmsg) {
		db.execSQL(
				"INSERT INTO " + DBHelper.TABLE_MESSAGE
						+ " VALUES(?, ?, ?, ?,?, ?, ?, ?,?, ?, ?, ?,?)",
				new Object[] { chatmsg.getMessageId(),
						chatmsg.getMessageContent(),
						chatmsg.getMessageDirection(),
						chatmsg.getMessageType(), 
						chatmsg.getIsRead(),
						chatmsg.getImState(),
						chatmsg.getMessagetime().getTime(),
						chatmsg.getFromuser().getUserid(),
						chatmsg.getMediaUrl(), chatmsg.getMediaPath(),
						chatmsg.getMediaduration(), chatmsg.getImageWidth(),
						chatmsg.getImageHeight() });

	}

	/**
	 * 保存多条消息
	 * 
	 * @param chatmsgs
	 */
	public void save(List<IMChatMessage> chatmsgs) {
		// 消息表
		db.beginTransaction(); // 开始事务
		try {
			for (IMChatMessage chatmsg : chatmsgs) {
				db.execSQL(
						"INSERT INTO " + DBHelper.TABLE_MESSAGE
								+ " VALUES(?, ?, ?, ?,?, ?, ?, ?,?, ?, ?, ?,?)",
						new Object[] { chatmsg.getMessageId(),
								chatmsg.getMessageContent(),
								chatmsg.getMessageDirection(),
								chatmsg.getMessageType(),
								chatmsg.getIsRead(),
								chatmsg.getImState(),
								chatmsg.getMessagetime().getTime(),
								chatmsg.getFromuser().getUserid(),
								chatmsg.getMediaUrl(), chatmsg.getMediaPath(),
								chatmsg.getMediaduration(),
								chatmsg.getImageWidth(),
								chatmsg.getImageHeight() });
			}
			db.setTransactionSuccessful(); // 设置事务成功完成
		} finally {
			db.endTransaction(); // 结束事务
		}

	}

	/**
	 * 删除指定用户的消息
	 * 
	 * @param fromUserId
	 *            消息的发送者id
	 */
	public void deleteMessageByFromUserId(String fromUserId) {
		db.execSQL("DELETE FROM " + DBHelper.TABLE_MESSAGE
				+ " WHERE fromUserId='" + fromUserId + "'");
	}

	/**
	 * 删除指定的消息
	 * 
	 * @param fromUserId
	 *            消息的 id
	 */
	public void deleteMessageById(String id) {
		db.execSQL("DELETE FROM " + DBHelper.TABLE_MESSAGE + " WHERE msgId='"
				+ id + "'");
	}

	/**
	 *更新消息的已读未读状态
	 * @param id 消息id
	 * @param state 消息状态
	 */
	public void updateMessageReadState(String id, int state ,int imState ) {
		   ContentValues cv = new ContentValues();
	        cv.put("isRead", state);
	        cv.put("imState", imState);
	        String[] args = {id};
	        db.update(DBHelper.TABLE_MESSAGE, cv, "msgId=?",args); 
//		db.execSQL("UPDATE " + DBHelper.TABLE_MESSAGE + " SET isRead=" + state
//				+ " WHERE msgId='" + id + "'");
	}

	
	/**
	 * 根据id查询是否存在该消息
	 * @param id
	 * @return
	 */
	public boolean queryMessagesById(String id) {
		Cursor c = db.rawQuery("select * from " + DBHelper.TABLE_MESSAGE
				+ " WHERE msgId like ?  " , new String[] {id});
		 if(c != null && c.moveToFirst()){  
			 return true;
		 }
		c.close();
		return false;
	}
	/**
	 * 查询指定用户指定的消息状态 消息总数
	 * @param fromuserId  发送消息用户id
	 * @param readstate 消息已读或未读
	 * @return
	 */
	public int getMessagesCountByFromUserId(
			String fromuserId, int readstate) {
		int count = 0;
		Cursor c = db.rawQuery("select count(*) from " + DBHelper.TABLE_MESSAGE
				+ " WHERE fromUserId like ? and isRead like ?   " , new String[] {fromuserId,String.valueOf(readstate)});
		   if(c.moveToNext()){
		           count = c.getInt(0);
		   }
	 
		c.close();
		return count;
	}
	
	/**
	 * 查询未读消息总数
	 * @return
	 */
	public int getUnReadMessagesCount() {
		int count = 0;
		Cursor c = db.rawQuery("select count(*) from " + DBHelper.TABLE_MESSAGE
				+ " WHERE isRead like ?   " , new String[] {String.valueOf(IMChatMessage.STATE_UNREAD)});
		   if(c.moveToNext()){
		           count = c.getInt(0);
		   }
	 
		c.close();
		return count;
	}
	
	public List<IMChatMessage> queryMessagesByFromUserId(
			String fromuserId, int page) {
		 DBContactUser fromuser	= queryUserById(fromuserId);
		    if(fromuser == null)
		    	return null;
		    
		List<IMChatMessage> msglist = new ArrayList<IMChatMessage>();
		Cursor c = db.rawQuery("select * from " + DBHelper.TABLE_MESSAGE
				+ " WHERE fromUserId like ? order by time desc limit " + pageSize
				+ " offset " + page, new String[] { fromuserId});
		while (c.moveToNext()) {
			IMChatMessage msg = new IMChatMessage();
			msg.setFromuser(fromuser);
			msg.setImageHeight(c.getInt(c.getColumnIndex("imageHeight")));
			msg.setImageWidth(c.getInt(c.getColumnIndex("imageWidth")));
			msg.setIsRead(c.getInt(c.getColumnIndex("isRead")));
			msg.setImState(c.getInt(c.getColumnIndex("imState")));
			msg.setMediaduration(c.getInt(c.getColumnIndex("mediaDuration")));
			msg.setMediaPath(c.getString(c.getColumnIndex("mediaPath")));
			msg.setMediaUrl(c.getString(c.getColumnIndex("mediaUrl")));
			msg.setMessageContent(c.getString(c.getColumnIndex("msgContent")));
			msg.setMessageDirection(c.getInt(c.getColumnIndex("msgDirection")));
			msg.setMessageId(c.getString(c.getColumnIndex("msgId")));
			msg.setMessagetime(new Date(c.getLong(c.getColumnIndex("time"))));
			msg.setMessageType(c.getInt(c.getColumnIndex("msgType")));
			msglist.add(msg);
		}
		c.close();
		return msglist;
	}
   
	/**
	 * 查询用户聊天窗口首次显示消息
	 * 若有未读消息则显示未读消息
	 * 若无未读消息则显示最近3条消息
	 * @param fromuser
	 * @return
	 */
	public List<IMChatMessage> queryMessagesFirstdiplayByFromUserId(
			String fromuserId) {
	    DBContactUser fromuser	= queryUserById(fromuserId);
	    if(fromuser == null)
	    	return null;
		List<IMChatMessage> msglist = new ArrayList<IMChatMessage>();
		//查询未读消息
		Cursor c = db.rawQuery("select * from " + DBHelper.TABLE_MESSAGE
				+ " WHERE fromUserId like ? and isRead like ? order by time desc limit " + pageSize
				+ " offset " + 0, new String[] { fromuserId,String.valueOf(IMChatMessage.STATE_UNREAD)});
		while (c.moveToNext()) {
			IMChatMessage msg = new IMChatMessage();
			msg.setFromuser(fromuser);
			msg.setImageHeight(c.getInt(c.getColumnIndex("imageHeight")));
			msg.setImageWidth(c.getInt(c.getColumnIndex("imageWidth")));
			msg.setIsRead(c.getInt(c.getColumnIndex("isRead")));
			msg.setImState(c.getInt(c.getColumnIndex("imState")));
			msg.setMediaduration(c.getInt(c.getColumnIndex("mediaDuration")));
			msg.setMediaPath(c.getString(c.getColumnIndex("mediaPath")));
			msg.setMediaUrl(c.getString(c.getColumnIndex("mediaUrl")));
			msg.setMessageContent(c.getString(c.getColumnIndex("msgContent")));
			msg.setMessageDirection(c.getInt(c.getColumnIndex("msgDirection")));
			msg.setMessageId(c.getString(c.getColumnIndex("msgId")));
			msg.setMessagetime(new Date(c.getLong(c.getColumnIndex("time"))));
			msg.setMessageType(c.getInt(c.getColumnIndex("msgType")));
			msglist.add(msg);
		}
		c.close();
		if(msglist.size() == 0){
			c = db.rawQuery("select * from " + DBHelper.TABLE_MESSAGE
					+ " WHERE fromUserId like ? order by time desc limit " + 3
					+ " offset " + 0, new String[] {fromuserId});
			while (c.moveToNext()) {
				IMChatMessage msg = new IMChatMessage();
				msg.setFromuser(fromuser);
				msg.setImageHeight(c.getInt(c.getColumnIndex("imageHeight")));
				msg.setImageWidth(c.getInt(c.getColumnIndex("imageWidth")));
				msg.setIsRead(c.getInt(c.getColumnIndex("isRead")));
				msg.setImState(c.getInt(c.getColumnIndex("imState")));
				msg.setMediaduration(c.getInt(c.getColumnIndex("mediaDuration")));
				msg.setMediaPath(c.getString(c.getColumnIndex("mediaPath")));
				msg.setMediaUrl(c.getString(c.getColumnIndex("mediaUrl")));
				msg.setMessageContent(c.getString(c.getColumnIndex("msgContent")));
				msg.setMessageDirection(c.getInt(c.getColumnIndex("msgDirection")));
				msg.setMessageId(c.getString(c.getColumnIndex("msgId")));
				msg.setMessagetime(new Date(c.getLong(c.getColumnIndex("time"))));
				msg.setMessageType(c.getInt(c.getColumnIndex("msgType")));
				msglist.add(msg);
			}
		}
		c.close();
		return msglist;
	}
	
	
	//==========================DBContactUser=================================
	/**
	 * 插入或者更新
	 * 
	 * @param user
	 */
	public void saveOrUpdate(DBContactUser user) {
		if(user == null)
			return;
		db.execSQL("REPLACE  INTO " + DBHelper.TABLE_CONTACTUSER
				+ " VALUES(?, ?, ?, ?,?)", new Object[] { user.getUserid(),
				user.getHeardurl(), user.getNickname(), user.getLastContent(),
				user.getTime() });

	}

	/**
	 * 删除联系人【删除前需删除对应联系人消息】
	 * @param id
	 */
	public void deleteUserById(String id) {
		db.execSQL("DELETE FROM " + DBHelper.TABLE_CONTACTUSER
				+ " WHERE userId='" + id + "'");
	}
	
    /**
     * 分页查询联系人列表
     * @param page
     * @return
     */
	public DBContactUser queryUserById(String userId) {
//		String ord = (sort==null|| sort.toLowerCase().startsWith("a"))?"asc":"desc";
		DBContactUser user = null;
		Cursor c = db.rawQuery("select * from " + DBHelper.TABLE_CONTACTUSER+ " WHERE userId like ? " , new String[] {userId});
		if (c.moveToFirst()) {
			 user = new DBContactUser();
			user.setHeardurl(c.getString(c.getColumnIndex("heardUrl")));
			user.setLastContent(c.getString(c.getColumnIndex("lastContent")));
			user.setNickname(c.getString(c.getColumnIndex("nickName")));
			user.setTime(new Date(c.getLong(c.getColumnIndex("time"))));
			user.setUserid(c.getString(c.getColumnIndex("userId")));
		}
		c.close();
		return user;
	}

      /**
       * 分页查询联系人列表
       * @param page
       * @return
       */
	public List<DBContactUser> queryUserList(int page) {
//		String ord = (sort==null|| sort.toLowerCase().startsWith("a"))?"asc":"desc";
		List<DBContactUser> userlist = new ArrayList<DBContactUser>();
		Cursor c = db.rawQuery("select * from " + DBHelper.TABLE_CONTACTUSER
				+ " order by time desc limit " + pageSize
				+ " offset " + page, null);
		while (c.moveToNext()) {
			DBContactUser user = new DBContactUser();
			user.setHeardurl(c.getString(c.getColumnIndex("heardUrl")));
			user.setLastContent(c.getString(c.getColumnIndex("lastContent")));
			user.setNickname(c.getString(c.getColumnIndex("nickName")));
			user.setTime(new Date(c.getLong(c.getColumnIndex("time"))));
			user.setUserid(c.getString(c.getColumnIndex("userId")));
			userlist.add(user);
		}
		c.close();
		return userlist;
	}

	
	
	public void closeDB() {
		db.close();
	}
}
